
/** 字符串截取省略号替代 */
export function truncateName(name, maxLength) {
  if(!name || name === ""){
    return "";
  }
  if (name.length > maxLength) {
    return name.slice(0, maxLength - 3).trim() + "...";
  }
  return name;
}

/** 对象转表单对象 */
export function toFormData(data) {
  let formData = new FormData();
  for (let key in data) {
    formData.append(key, data[key]);
  }
  return formData;
}

/**字节转换，返回单位和大小组成的对象 */
export function bytesToSize(bytes) {
  if (bytes === 0) return { size: 0, unit: "B" };
  let k = 1024;
  let sizes = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
  let i = Math.floor(Math.log(bytes) / Math.log(k));
  return {
    size: parseFloat((bytes / Math.pow(k, i)).toFixed(2)),
    unit: sizes[i],
  };
}

/**
 *
 * @param startTime 开始时间
 * @param endTime 结束时间
 * @returns 差值
 */
export function getDateDiff(startTime, endTime) {
  if (!startTime || !endTime) {
    return "";
  }
  //将日期字符串转换为时间戳
  let sTime = new Date(startTime).getTime(); //开始时间
  let eTime = new Date(endTime).getTime(); //结束时间
  let divNumSecond = 1000;
  /** 换算成秒 */
  const diff = (eTime - sTime) / divNumSecond;
  if (diff > 60 && (diff / 60 < 60)) {
    // 超过分钟但没有超过小时，按分钟算
    let miniute = Math.floor(diff / 60);
    let second = diff % 60;
    return second === 0 ? `${miniute}分钟`:`${miniute}分钟,${second}秒`;
  } else if(diff > 3600 && (diff/3600) < 24 ) {
    // 超过小时但没有超过天，按小时，分钟，秒算
    let hour = Math.floor(diff / 3600);
    let minute = Math.floor((diff % 3600)/60)
    return minute === 0 ? + `${hour}小时`:`${hour}小时,${minute}分钟`;
  }else{
    return diff + "秒";
  }
}

export function removeEmptyValues(obj) {
  for (const key in obj) {
    if (obj[key] === null || obj[key] === undefined) {
      delete obj[key];
    } else if (typeof obj[key] === 'object' && Object.keys(obj[key]).length === 0) {
      delete obj[key];
    }
  }
  return obj;
}
